<template>
	<view class="main">
		<delVue :Visible="isshow" @isModal="modal" @goStay="stay" :oneText="one" :twoText="two" :threeText="three"
			:fourText="four" />
		<view class="">
			<alltitleVue :title="title" :url="url" />
		</view>
		<view class="public">
			<view class="public-tit">
				<!-- <view class="">
					就诊人
				</view> -->
				<image :src="userAvatar" alt="用户头像" @click="chooseImage"  />
			</view>
			<view class="container">
				<!-- 姓名 -->
				<view class="form-item">
					<view class="input-box">
						<text class="label">姓名</text>
						<input v-model="add.name" :disabled="disabled" placeholder="请输入姓名" 
							@blur="validateName" class="input" />
					</view>
					<view class="error-box">
					</view>
				</view>
				<!-- 身份证号 -->
				<view class="form-item">
					<view class="input-box">
						<text class="label">身份证号</text>
						<input v-model="add.idCard" :disabled="disabled" placeholder="请输入身份证号" 
							class="input" />
					</view>
					<view class="error-box">

					</view>


				</view>

				<!-- 性别 -->
				<view class="form-item item-box">
					<text class="label">性别</text>
					<view class="gender" @click="noInput">
						<text :class="{'highlight': add.gender === '男'}" class="gender-label">男</text>
						<text :class="{'highlight': add.gender === '女'}" class="gender-label">女</text>
					</view>
				</view>

				<!-- 电话号码 -->
				<view class="form-item">
					<view class="input-box">
						<text class="label">电话号码</text>
						<input v-model="add.mobile" :disabled="disabled" placeholder="请输入电话号码" 
							class="input" />
					</view>
					<view class="error-box">

					</view>
				</view>
				<!-- 出生年月日 -->
				<view class="form-item">
					<view class="input-box">
						<text class="label">出生日期</text>
						<input v-model="birthDate" disabled="true" class="input" />
					</view>
					
				</view>

			</view>

		</view>
		<view class="btn-box">

			<!-- <button v-if="cardid.ids==''" @click="submitForm" class="submit-btn">添加就诊卡</button> -->
			<view class="btn-xiu">
				<!-- <view class="" @click="deleteItem(item)">
					删除
				</view> -->
				<view class="" @click="edit">
					保存
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	import config from "../../utils/config";
	import delVue from '../../components/del.vue'
	import {

		memberDelete,
		setMember,
	} from "@/service/api.js";
	import {
		toast,
		setStore,
		getStore,
		getDate,
		validateIdCard,

	} from "@/utils";
	export default {
		components: {
			delVue
		},
		computed: {
			// 动态构建上传的 header
			uploadHeaders() {
				return {
					Authorization: `Bearer ${this.token}`, // 把 token 加到请求头中
					'Custom-Header': 'CustomValue', // 如果需要其他自定义头部，添加这里
					"clientid": "af80f6d0dc2d2f09587d2bd25e384d84"
				};
			}
		},
		data() {
			return {
				userAvatar: config.ossHost + "2025/01/06/0f26de75078d48d0853a65ff9709b6e0.png", 
				disabled: false,
				information: false,
				isshow: false,
				one: "再想想",
				two: "确定删除",
				three: "确定要删除此用户信息吗？",
				four: "删除提示",
				title: "个人资料",
				add: {
					name: '',
					iscard: 0,
					idCard: '',
					gender: '', // 自动识别的性别
					mobile: '',
					id: "",
					photo: config.ossHost+"2025/01/06/0f26de75078d48d0853a65ff9709b6e0.png",
				},
				
				birthDate: "",
				nameError: '',
				idCardError: '',
				phoneError: '',
				cardid: {
					ids: ""
				},
				token: "",
				url: config.host,

			}
		},
		onLoad(options) {
			let info = JSON.parse(getStore('info'));
			this.token = getStore("token")
			if (info) {
				this.cardid.ids = info.id;
				this.cardinfo = info;
				this.add.name = this.cardinfo.name;
				this.add.idCard = this.cardinfo.idCard;
				this.add.mobile = this.cardinfo.mobile;
				this.add.photo = this.cardinfo.photo;
				this.userAvatar=this.cardinfo.photo
				// 自动识别性别
				this.autoIdentifyGender();
				this.extractBirthDate()
			}
			if (options.information) {
				this.information = options.information
			}

		},
		methods: {
			chooseImage() {
				uni.chooseImage({
					count: 1, // 选择一张图片
					sizeType: ['original', 'compressed'], // 选择原图或压缩图
					sourceType: ['album', 'camera'], // 可以选择来自相册或拍照
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						this.uploadAvatar(tempFilePaths[0]); // 选择完图片后上传
					},
					fail: (err) => {
						console.log('选择图片失败', err);
					}
				});
			},

			uploadAvatar(filePath) {
				uni.uploadFile({
					url: this.url + 'resource/oss/upload',
					// 服务器上传接口
					filePath: filePath,
					header: {
						'Authorization': `Bearer ${this.token}`, // 把 token 加到请求头中
						'Custom-Header': 'CustomValue', // 如果需要其他自定义头部，添加这里
						"clientid": "af80f6d0dc2d2f09587d2bd25e384d84"
					},
					name: 'file', // 上传文件的字段名
					success: (uploadRes) => {
						const data = JSON.parse(uploadRes.data);
						if (data.code === 200) {
							
							// 头像上传成功，获取头像的 URL
							this.updateAvatar(data.data.url); // 更新头像URL
						} else {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.log('上传头像失败', err);
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						});
					}
				});
			},
			// 更新用户头像
			updateAvatar(avatarUrl) {
				// 更新头像 URL
				this.add.photo = avatarUrl;

				// 将新头像保存到本地存储
				// uni.setStorageSync('userInfo', this.user);

				// 更新头像显示
				this.userAvatar = avatarUrl;
				console.log(avatarUrl, "这里是否拿到头像")

				// 显示更新成功提示
				uni.showToast({
					title: '头像更新成功',
					icon: 'success'
				});
			},



			stay(item) {
				this.isshow = item;

				this.deleteHandle();

			},
			edit() {
				this.submitForm();
			},
			extractBirthDate() {
				// 身份证号必须是18位
				if (this.add.idCard && this.add.idCard.length === 18) {
					const birthStr = this.add.idCard.slice(6, 14); // 获取第7位到14位的日期部分
					const year = birthStr.slice(0, 4); // 年
					const month = birthStr.slice(4, 6); // 月
					const day = birthStr.slice(6, 8); // 日

					// 格式化为 yyyy-MM-dd
					this.birthDate = `${year}-${month}-${day}`;
				} else {
					this.birthDate = ''; // 如果身份证号不合法，清空出生日期
				}
			},




			// 姓名验证
			validateName() {
				if (!this.add.name) {
					this.nameError = '姓名不能为空';
					toast(this.nameError)
				} else {
					this.nameError = '';
				}
			},
			onImageError() {
				// 图片加载失败时，切换为错误图片
				this.userAvatar = this.errorAvatar; // 可以在这里设置一个默认的错误图
				
			},
			// 身份证验证
			validateIdCard() {
				const idCardPattern = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\d{3}[0-9Xx]$/;
				if (!this.add.idCard) {
					this.idCardError = '身份证号不能为空';
					toast(this.idCardError)
				} else if (!idCardPattern.test(this.add.idCard)) {
					this.idCardError = '身份证号格式不正确';
					toast(this.idCardError)
				} else {
					this.idCardError = '';
					this.autoIdentifyGender(); // 身份证号验证通过后自动识别性别
				}
			},

			// 性别自动识别
			autoIdentifyGender() {
				if (this.add.idCard && this.add.idCard.length === 18) {
					const genderCode = parseInt(this.add.idCard[16]); // 取身份证号的第17位
					this.add.gender = genderCode % 2 === 0 ? '女' : '男'; // 偶数为女，奇数为男
				}
			},

			// 电话号码验证
			validatePhone() {
				const phonePattern = /^1[3-9]\d{9}$/;
				if (!this.add.mobile) {
					this.phoneError = '电话号码不能为空';
					toast(this.phoneError)
				} else if (!phonePattern.test(this.add.mobile)) {
					this.phoneError = '电话号码格式不正确';
					toast(this.phoneError)
				} else {
					this.phoneError = '';
				}
			},
			noInput() {
				toast("该信息可根据身份证自动计算，无需填写");
			},
			deleteItem() {

				this.isshow = true

			},

			async getInfo(accessToken) {
				try {
					const response = await uni.request({
						url: this.url + 'app/member/getInfo', // 注意这里的拼接，如果 this.url 为 undefined 会出错
						method: 'GET',
						header: {
							'Authorization': `Bearer ${accessToken}`, // 将 token 添加到请求头
							'content-type': 'application/json',
						},
					});

					if (response && response.data) {
						console.log('请求成功:', response.data);
						this.add=response.data.data.member;
						this.userAvatar=response.data.data.member.photo;
						setStore("info", JSON.stringify(response.data.data.member));
						return response.data;
					} else {
						console.log('没有获取到数据');
					}
				} catch (error) {
					console.error('请求失败:', error);
				}
			},



			async deleteHandle(item) {
				const res = await memberDelete(this.cardid);
				if (res.code == 200) {
					toast("删除成功");
					this.getInfo(this.token);
				}
			},
			// 提交表单
			async submitForm() {

				this.validateName();
				// if (this.nameError != '') {
				// 	return
				// }
				this.validateIdCard();
				// if (this.idCardError != '') {
				// 	return
				// }
				this.validatePhone();



				this.info = JSON.parse(getStore("info")) || {};
				this.add.id = this.info.id;
				
				let res = await setMember(this.add);
				if (res.code == 200) {
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
					this.getInfo(this.token);
					setTimeout(() => {
						uni.switchTab({
						  url: '/pages/my/index'
						})
					},1000)

				}




			}
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		height: 100vh;
		background: #F5F3F0;
	}

	.public {
		padding: 24rpx;
		margin: 0 24rpx;
		background: #FFFFFF;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
		margin-top: 32rpx;

		.public-tit {
			display: flex;
			justify-content: center;
			font-weight: bold;
			font-size: 32rpx;
			margin-bottom: 24rpx;

			image {
				width: 112rpx;
				height: 112rpx;
				border-radius: 50%;
			}
		}

		.container {

			// padding: 20rpx;
			.form-item {
				border-bottom: 1rpx solid #E6E6E6;

				.input-box {
					display: flex;
					align-items: center;
					justify-content: space-between;
				}

				margin-bottom: 24rpx;
			}

			.form-item:last-child {
				border-bottom: 0;
				margin-bottom: 0;
			}

			.label {
				display: inline-block;
				width: 100rpx;
				font-size: 24rpx;
				margin-right: 48rpx;
			}

			.input {
				text-align: end;
				color: #808080;
				font-size: 24rpx;


			}
		}

		.error-box {
			height: 24rpx;
			display: flex;
		}

		.item-box {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 24rpx;
			padding-bottom: 24rpx;

			.gender {
				display: flex;
				align-items: center;
			}

			.gender-label {
				display: inline-block;
				width: 48rpx;
				height: 48rpx;
				line-height: 48rpx;
				text-align: center;
				margin-right: 15rpx;
				background: #F8F8F8;
				border-radius: 50%;

			}

			.highlight {
				font-weight: bold;
				background: #CCA566;
				color: #fff;

			}
		}


	}

	.btn-box {
		position: fixed;
		bottom: 0;
		background: #fff;
		padding-top: 24rpx;
		width: 100%;
		height: 130rpx;


		.submit-btn {
			width: 702rpx;
			margin: auto;
			height: 86rpx;
			line-height: 86rpx;
			background: #CCA566;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			font-weight: bold;
			font-size: 32rpx;
			color: #fff;
			border-radius: 16rpx;
		}

		.btn-xiu {
			display: flex;
			justify-content: space-between;
			width: 702rpx;
			margin: auto;

			view {
				width: 702rpx;
				height: 86rpx;
				line-height: 86rpx;
				text-align: center;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				border: 2rpx solid #CCA566;
				background: #fff;
				color: #CCA566;
			}

			view {
				background: #CCA566;
				color: #fff;
			}
		}

	}
</style>